{% extends "base.html" %}
{% block content %}
    <div class="card shadow-sm p-4 mb-4 bg-white rounded">
        <form method="get" class="row g-3 align-items-center">
            <!-- 第一列：创建老师 -->
            <div class="col-md-3">
                <input type="text" class="form-control" name="created_by" placeholder="创建老师">
            </div>
            <!-- 第二列：题目名称 -->
            <div class="col-md-3">
                <input type="text" class="form-control" name="title" placeholder="题目名称">
            </div>
            {% if not request.user.is_student %}
            <!-- 第三列：状态选择 -->
            <div class="col-md-3">
                <select class="form-select" name="status">
                    <option value="" disabled selected>全部</option>
                    <option value="draft">草稿</option>
                    <option value="pending">待审核</option>
                    <option value="approved">已通过</option>
                    <option value="rejected">未通过</option>
                </select>
            </div>
            {% endif %}
            <!-- 第四列：查询按钮 -->
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-25 ">查询</button>
            </div>
        </form>
    </div>
    
    <div>
    <!-- 创建题目按钮 -->
    {% if not request.user.is_student %}
        <div style="margin-bottom: 10px;">
        <button type="button" class="btn btn-primary create-btn" data-bs-toggle="modal" data-bs-target="#questionModal">
            创建题目
        </button>
    </div>
    {% endif %}

    <!-- 复用的模态框（创建/编辑共用） -->
    <div class="modal fade" id="questionModal" tabindex="-1" aria-labelledby="questionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="questionModalLabel">题目管理</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="questionForm" method="post">
                        {% csrf_token %}
                        <input type="hidden" name="id" id="questionId"> <!-- 编辑时传递ID -->
                        
                        <!-- 创建/编辑共用表单字段 -->
                        <div class="mb-3">
                            <label class="form-label">题目名称</label>
                            <input type="text" class="form-control" name="title" id="questionTitle" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">题目要求</label>
                            <textarea class="form-control" name="content" id="questionContent" rows="3" required></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">最大选题人数</label>
                            <input type="number" class="form-control" name="max_students"
                                   id="questionMaxStudents" min="1" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select class="form-select" name="status" id="questionStatus"
                                    required>
                                <option value="draft">草稿</option>
                                <option value="pending">待审核</option>
                                {% if request.user.is_admin %}
                                <option value="approved">已通过</option>
                                <option value="rejected">未通过</option>
                                {% endif %}
                            </select>
                        </div>

                        <!-- 隐藏的创建者字段（自动填充当前用户） -->
                        <input type="hidden" name="created_by" value="{{ request.user.id }}">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm p-4 mb-4 bg-white rounded">
        <style>               
         tr,td {
             text-align: center;
             vertical-align: middle;
             
         }
        </style>
        <table class="table table-hover">
            <thead>
            <tr>
                <th scope="col">题目ID</th>
                <th scope="col">题目名称</th>
                <th scope="col">题目要求</th>
                <th scope="col">最大选题人数</th>
                <th scope="col">当前选题人数</th>
                <th scope="col">状态</th>
                <th scope="col">创建教师</th>
                <th scope="col">创建时间</th>
                {% if not request.user.is_student %}
                <th scope="col">操作</th>
                {% endif %}
            </tr>
            </thead>
            <tbody>
            {% for question in questions %}
            <tr>
                <th scope="row" >{{ question.id }}</th>
                <td>{{ question.title }}</td>
                <td>{{ question.content }}</td>
                <td>{{ question.max_students }}</td>
                <td>{{ question.current_students }}</td>
                <td>{{ question.status }}</td>
                <td>{{ question.created_by }}</td>
                <td>{{ question.created_at | date:"Y-m-d H:i:s"}}</td>
                {% if not request.user.is_student %}
                <td>
                    
                    <button type="button" class="btn btn-primary edit-btn {% if request.user.is_teacher and question.status == '已通过'  %}disabled{% endif %}"

                            data-bs-toggle="modal" data-bs-target="#questionModal"
                            data-question-id="{{ question.id }}"
                            data-title="{{ question.title }}"
                            data-content="{{ question.content }}"
                            data-max-students="{{ question.max_students }}"
                            data-status="{{ question.status }}">
                            编辑
                    </button>
                    <form action="{% url 'delete_question' question.id %}" method="post" style="display: inline;">
                        {% csrf_token %}
                        <button type="button" class="btn btn-danger
                    {% if request.user.is_teacher and question.status == '已通过'  %}disabled{% endif %}"
                                onclick="confirmDelete(this)">删除</button>
                    </form>


                </td>
            {% endif %}
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    <div>
        <a href="?page={{ current_page | add:'-1' }}" class="btn btn-sm btn-primary">上一页</a> 
        <span>&lt;当前页：{{ current_page }}/{{ total_pages }}&gt;</span>
        <a href="?page={{ current_page | add:'1' }}" class="btn btn-sm btn-primary">下一页</a>
    </div>
    </div>

<script>
    function confirmDelete(button) {
    if (confirm('确定要删除这个题目吗？')) {
        const form = button.closest('form');
        const url = form.action;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('删除成功');
                window.location.reload();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('网络错误，请重试');
        });
    }
}

    document.addEventListener('DOMContentLoaded', function () {
        const modal = new bootstrap.Modal(document.getElementById('questionModal'));
        const form = document.getElementById('questionForm');
        const submitBtn = document.getElementById('submitBtn');
        let isEditMode = false;
        // 初始化表单
        function resetForm() {
            form.reset();
            document.getElementById('questionId').value = '';
            isEditMode = false;
            submitBtn.textContent = '保存';
        }
        
        // 点击【创建题目】按钮时触发
        document.querySelector('.create-btn').addEventListener('click', function () {
            resetForm();  // 清空表单
            modal.show(); // 显示模态框

        });
        function changeEnglish(status){
            var status_en = status;
            if(status === '草稿'){
                status_en = 'draft';
            }else if (status === '待审核'){
                status_en = 'pending';
            }else if (status === '已通过'){
                status_en = 'approved';
            }else if (status === '未通过'){
                status_en = 'rejected';
            }
            return status_en;
        }

        // 给所有 .edit-btn 添加点击事件监听器
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', function () {
                // 获取 data-* 属性中的数据
                const questionId = this.getAttribute('data-question-id');
                const title = this.getAttribute('data-title');
                const content = this.getAttribute('data-content');
                const maxStudents = this.getAttribute('data-max-students');
                const status = this.getAttribute('data-status');
                const status_en = changeEnglish(status);
                

                // 填充表单字段
                document.getElementById('questionId').value = questionId;
                document.getElementById('questionTitle').value = title;
                document.getElementById('questionContent').value = content;
                document.getElementById('questionMaxStudents').value = maxStudents;
                document.getElementById('questionStatus').value =  status_en;
                
                isEditMode = true;
                submitBtn.textContent = '更新';
                // 显示模态框
               
                modal.show();
            });
        });
        // 表单提交逻辑
        document.getElementById('submitBtn').addEventListener('click', function (e) {
            
            e.preventDefault();
            
            const formData = new FormData(form);
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            const questionId = document.getElementById('questionId').value;

            const url = questionId 
                ? `/question/${questionId}/update/` 
                : '/question/create/';

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrfToken,
                },
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message)
                    window.location.reload(); // 刷新页面获取最新数据
                } else {
                    alert(data.message)
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('网络请求失败，请重试');
            });
        });
    });
</script>

{% endblock %}
